package com.lz.yz.empowerment.service.impl;
import com.github.pagehelper.PageHelper;
import com.lz.yz.base.common.ValidatorUtil;
import com.lz.yz.base.entity.ReturnValue;
import com.lz.yz.base.util.DateUtil;
import com.lz.yz.base.util.StringUtil;
import com.lz.yz.core.AbstractService;
import com.lz.yz.empowerment.Param.QuestionParam;
import com.lz.yz.empowerment.Param.ShareOrderCount;
import com.lz.yz.empowerment.Param.ShareOrderParam;
import com.lz.yz.empowerment.dao.QuestionBuffMapper;
import com.lz.yz.empowerment.dao.QuestionLableMapper;
import com.lz.yz.empowerment.dao.QuestionShareMapper;
import com.lz.yz.empowerment.entity.QuestionBuff;
import com.lz.yz.empowerment.entity.QuestionLable;
import com.lz.yz.empowerment.entity.QuestionShare;
import com.lz.yz.empowerment.model.*;
import com.lz.yz.empowerment.service.QuestionBuffService;
import com.lz.yz.home.dao.DomainMapper;
import com.lz.yz.home.entity.Domain;
import com.lz.yz.member.dao.AttentionsMapper;
import com.lz.yz.member.dao.LableMapper;
import com.lz.yz.member.dao.UserLableMapper;
import com.lz.yz.member.entity.Attentions;
import com.lz.yz.member.entity.Lable;
import com.lz.yz.member.entity.Member;
import com.lz.yz.member.entity.UserLable;
import com.lz.yz.member.param.AttentionsParam;
import com.lz.yz.member.service.MemberService;
import com.lz.yz.order.dao.OrdersMapper;
import com.lz.yz.order.entity.Orders;
import com.lz.yz.order.enumeration.OrderStatus;
import com.lz.yz.order.enumeration.OrderType;
import com.lz.yz.order.service.OrdersService;
import com.lz.yz.outing.service.PushService;
import com.lz.yz.outing.service.SyncLockService;
import com.lz.yz.outing.util.ToolUtil;
import com.util.common.Page;
import com.util.common.QueryList;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;



@Service
@Transactional
public class QuestionBuffServiceImpl extends AbstractService<QuestionBuff> implements QuestionBuffService {

    @Autowired
    private QuestionBuffMapper questionBuffMapper;

    @Autowired
    SyncLockService syncLockService;

    @Autowired
    private QuestionLableMapper questionLableMapper;

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private QuestionShareMapper questionShareMapper;

    @Autowired
    private OrdersService ordersService;


    @Autowired
    private DomainMapper domainMapper;


    @Autowired
    private LableMapper lableMapper;

    @Autowired
    private UserLableMapper  userLableMapper;

    @Autowired
    private MemberService memberService;

    @Autowired
    private AttentionsMapper attentionsMapper;

    @Autowired
    private PushService pushService;


    @Resource(name = "redisTemplate")
    private RedisTemplate<String, QuestionModel> redisTemplate;

    /**
     *  发布赋能
     * @param
     * @return
     */
    @Override
    public ReturnValue add(QuestionModel questionModel) {
        //控制双重点击事件
        if (!syncLockService.syncLock("addQuesetion/" + questionModel.getAccountId() , 5, TimeUnit.SECONDS)) {
            return ReturnValue.generateFalseReturnValue("请不要重复提交!");
        }

        if(!memberService.validateAccountIntact(questionModel.getAccountId())){
            return ReturnValue.generateFalseReturnValue("该用户还未完善资料");
        }
        if(questionModel.getIntroduction().replaceAll(ValidatorUtil.REGEX_HTML,"").length()>400){
            return ReturnValue.generateFalseReturnValue("发布内容介绍不能超过350字!");
        }

        QuestionBuff questionBuff=new QuestionBuff();
        BeanUtils.copyProperties(questionModel,questionBuff);
        Domain domain=new Domain();
        domain.setId(questionModel.getDomainId());
        questionBuff.setTitle(StringUtil.filterEmoji(questionModel.getTitle()));
        questionBuff.setContent(StringUtil.filterEmoji(questionModel.getContent()));
        questionBuff.setIntroduction(StringUtil.filterEmoji(questionModel.getIntroduction()));
        domain= domainMapper.selectOne(domain);
        if(null!=domain){
            questionBuff.setDomainName(domain.getDomainName());
            //赋能对象保存
            int questionId=questionBuffMapper.insertSelective(questionBuff);
        }else{
            return ReturnValue.generateFalseReturnValue("赋能分类异常");
        }
        if (questionModel.getLabelIds() != null&&!questionModel.getLabelIds().equals("")) {
            String ids = questionModel.getLabelIds();
            String[] idArr = ids.split(",");
            for (String id : idArr) {
                QuestionLable questionLable=new QuestionLable();
                questionLable.setLableId(Integer.valueOf(id));
                questionLable.setQuestionId(questionBuff.getId());
                //赋能关联标签对象保存
                questionLableMapper.insertSelective(questionLable);
            }
        }
       if(questionModel.getQuestionTbId()!=null){
           redisTemplate.delete(questionModel.getQuestionTbId());
       }



        return ReturnValue.generateTrueMsgReturnValue("赋能发布成功");
    }


    /**
     *  通过分类ID查询赋能列表
     * @param
     * @return
     */
    @Override
    public ReturnValue listQuestion(QuestionParam param) {

        List<QuestionListModel> questionListModels= new ArrayList<>();
        List<QuestionBean>  questionBeans= new ArrayList<>();
        if(param.getTypeId()==1){
            param.setUserId(null);
            PageHelper.startPage(param.getPage(), param.getPageSize());
           questionBeans=questionBuffMapper.queryQuestionlist(param);
        }
        if(param.getTypeId()==2){
            // 查询首页推荐
           if(param.getUserId().equals("-1")){
               //无token推荐查询
               param.setUserId(null);
               param.setDomainId(null);
               PageHelper.startPage(param.getPage(), param.getPageSize());
               questionBeans=questionBuffMapper.queryQuestionlist(param);
           }else{
               //有token推荐查询
               UserLable userLable=new UserLable();
               userLable.setType(2);
               userLable.setAccountId(param.getUserId());
               List<UserLable> userLables=userLableMapper.select(userLable);

               //查询用户是否存在标签
               if(userLables.size()>0){
                   PageHelper.startPage(param.getPage(), param.getPageSize());
                   questionBeans=questionBuffMapper.queryRecommendQuestionlist(param);
                   if(questionBeans.size()<8){
                       param.setUserId(null);
                       param.setDomainId(null);
                       PageHelper.startPage(param.getPage(), param.getPageSize());
                       questionBeans=questionBuffMapper.queryQuestionlist(param);
                   }
               }else{
                   param.setUserId(null);
                   param.setDomainId(null);
                   PageHelper.startPage(param.getPage(), param.getPageSize());
                   questionBeans=questionBuffMapper.queryQuestionlist(param);
               }

           }

        }
        if(param.getTypeId()==3){
            //详情推荐赋能列表
            QuestionBuff questionBuff=new QuestionBuff();
            questionBuff.setId(param.getQuestionId());
            questionBuff= questionBuffMapper.selectOne(questionBuff);
            //param.setDomainId(questionBuff.getDomainId());
            PageHelper.startPage(param.getPage(), param.getPageSize());
            questionBeans=questionBuffMapper.queryRecommendQuestionlist(param);
        }
        if(param.getTypeId()==4){
            param.setUserId(param.getTargetUserId());
            param.setDomainId(null);
            PageHelper.startPage(param.getPage(), param.getPageSize());
            questionBeans=questionBuffMapper.queryAttentionQuestionlist(param);
        }
        if(null!=questionBeans){
            questionBeans.forEach(questionBean -> {
                QuestionListModel questionListModel=new QuestionListModel();
                BeanUtils.copyProperties(questionBean,questionListModel);
                QuestionParam param1=new QuestionParam();
                param1.setQuestionId(questionListModel.getId());
                List<LableBean> LableBeans= questionBuffMapper.queryLableList(param1);
                questionListModel.setLables(LableBeans);
                questionListModels.add(questionListModel);
            });
            QueryList<QuestionListModel> result = new QueryList(questionListModels, Page.toPage(questionBeans));
            return ReturnValue.generateTrueReturnValue(result);
        }

         return ReturnValue.generateTrueReturnValue("该分类下没有赋能");
    }

    /**
     *  通过赋能ID和用户ID查询赋能详情
     * @param
     * @return
     */
    @Override
    public ReturnValue queryQuestionDetails(QuestionParam param) {
        QuestionDetailsModel questionDetailsModel=new QuestionDetailsModel();
        QuestionBean questionBean=new QuestionBean();
        QuestionBuff questionBuff=new QuestionBuff();
        questionBuff.setId(param.getQuestionId());
        questionBuff= questionBuffMapper.selectOne(questionBuff);
        Orders orders=new Orders();
        orders.setBuyerAccountId(param.getUserId());
        orders.setObjectiveId(param.getQuestionId());
        orders.setOrderType(OrderType.QUESTIONBUFF.getStatusValue());//订单类型赋能
        orders.setStatus(OrderStatus.COMPLETE.getStatusValue());//已完成
         //List<Orders> ordersList= ordersMapper.select(orders);
        orders=ordersMapper.selectOne(orders);
        List<IsPayShareOrderBean> isPay=questionBuffMapper.queryShareIsPay(param);
        QuestionShare questionShare=new QuestionShare();
        questionShare.setQuestionId(param.getQuestionId());
        questionShare.setAccountId(param.getUserId());
        questionShare= questionShareMapper.selectOne(questionShare);
        if(null!=questionBuff){
            questionBean= questionBuffMapper.queryQuestionDetails(param);
            Integer num= questionBuffMapper.queryQuestionNumByPay(param);
            questionBean.setQuestionNum(num);
            BeanUtils.copyProperties(questionBean,questionDetailsModel);
            PageHelper.startPage(1, 5);
            List<Member> members=questionBuffMapper.queryTeachMember(param);
            questionDetailsModel.setMemberList(members);
            if(null!=questionShare){
                //发起平摊者
                if(questionShare.getStatus()==2){
                    questionDetailsModel.setIsShowContent(1);
                    questionDetailsModel.setIsComplete(1);
                    questionDetailsModel.setShareId(questionShare.getId());
                }else{
                    questionDetailsModel.setIsComplete(0);
                    questionDetailsModel.setIsShowContent(0);
                    questionDetailsModel.setShareId(questionShare.getId());
                    questionDetailsModel.setContent(null);
                }

                return ReturnValue.generateTrueReturnValue(questionDetailsModel);
            }
            if(isPay.size()>0){
                //发布者已参与平摊
                if(isPay.get(0).getStatus()==2){
                    questionDetailsModel.setIsShowContent(1);
                    questionDetailsModel.setIsComplete(1);
                    questionDetailsModel.setShareId(isPay.get(0).getShareId());
                }else{
                    questionDetailsModel.setIsShowContent(0);
                    questionDetailsModel.setIsComplete(0);
                    questionDetailsModel.setShareId(isPay.get(0).getShareId());
                    questionDetailsModel.setContent(null);
                }
              //  questionDetailsModel.setUserType(4);
                return ReturnValue.generateTrueReturnValue(questionDetailsModel);
            }

            if(questionBuff.getPrice().compareTo(new BigDecimal(0))==0){
                questionDetailsModel.setIsShowContent(1);
                return ReturnValue.generateTrueReturnValue(questionDetailsModel);
            }
            if(param.getUserId().equals(questionBuff.getAccountId())){
                //发布者
                questionDetailsModel.setIsShowContent(1);
                return ReturnValue.generateTrueReturnValue(questionDetailsModel);
            }
          if(null!=orders){
                if(param.getQuestionId().equals(orders.getObjectiveId())){
                    //已赋能用户
                  //  questionDetailsModel.setUserType(2);
                    questionDetailsModel.setIsShowContent(1);
                    return ReturnValue.generateTrueReturnValue(questionDetailsModel);
                }
          }
           // questionDetailsModel.setUserType(3);
            questionDetailsModel.setIsShowContent(0);
            questionDetailsModel.setContent(null);
            return ReturnValue.generateTrueReturnValue(questionDetailsModel);

        }

        return ReturnValue.generateTrueReturnValue("该赋能ID不存在");
    }



    /**
     *
     * @param通过赋能ID查询赋能人员信息
     * @return
     */
    @Override
    public ReturnValue querTeachMember(QuestionParam param){
        List<Member> members= questionBuffMapper.queryTeachMember(param);
        QueryList<Member> result = new QueryList(members, Page.toPage(members));
        return ReturnValue.generateTrueReturnValue(result);
    }


    /**
     * 赋能平摊记录保存
     * @param
     * @return
     */
    @Override
    public ReturnValue addShareLog(Integer accountId,ShareModel shareModel) {

        QuestionShare questionShare=new QuestionShare();
        questionShare.setAccountId(accountId);
        questionShare.setQuestionId(shareModel.getQuestionId());
        questionShare=questionShareMapper.selectOne(questionShare);
        if(null!=questionShare){
            return  ReturnValue.generateFalseReturnValue("同一个用户只能对一个赋能发起一次平摊");
        }
        QuestionShare questionShare1=new QuestionShare();
        QuestionBuff questionBuff=new QuestionBuff();
        questionBuff.setId(shareModel.getQuestionId());
        questionBuff=questionBuffMapper.selectOne(questionBuff);
        questionShare1.setaPrice(questionBuff.getPrice());
        questionShare1.setQuestionId(shareModel.getQuestionId());
        questionShare1.setaCount(shareModel.getaCount());
        questionShare1.setAccountId(accountId);
       // BeanUtils.copyProperties(shareModel,questionShare);
       int mun=questionShareMapper.insertSelective(questionShare1);
       if(mun>0){
           return  ReturnValue.generateTrueReturnValue("平摊记录保存成功",questionShare1.getId().toString());
       }else{
           return  ReturnValue.generateTrueReturnValue("平摊记录保存失败");

       }
    }



    /**
     * 查询赋能分享页面信息
     * @param
     * @return
     */
    @Override
    public ReturnValue queryShareInfo(QuestionParam param) {
        ShareInfoModel shareInfoModel=new ShareInfoModel();
        QuestionShare questionShare=new QuestionShare();
       // questionShare.setAccountId(param.getShareId()); // 平摊发起人
        questionShare.setId(param.getShareId());
        questionShare= questionShareMapper.selectOne(questionShare);
        ShareOrderParam shareOrderParam =new ShareOrderParam();
        shareOrderParam.setShareId(questionShare.getId());
         ShareOrderCount shareOrderCount=questionBuffMapper.queryShareOrderNumByPay(shareOrderParam);
         if(null==shareOrderCount.getTotalPrice()){
             BigDecimal priceClear= new BigDecimal( 0);
             shareOrderCount.setTotalPrice(priceClear);
         }
        shareInfoModel.setPaidAmount(shareOrderCount.getTotalPrice());
        shareInfoModel.setUnpaidAmount(questionShare.getaPrice().subtract(shareOrderCount.getTotalPrice()));
        if(null!=questionShare){
            if(questionShare.getStatus()==2){ //分摊记录表 该记录为已完成
                shareInfoModel.setIsPay(2); // 分享页面用户展示为已结束
            }else{
                Orders orders=new Orders();
                orders.setObjectiveId(questionShare.getId());
                orders.setBuyerAccountId(param.getUserId());
                orders.setOrderType(OrderType.FLAT.getStatusValue());
                orders.setShareQuestionId(questionShare.getQuestionId());
                orders.setStatus(OrderStatus.COMPLETE.getStatusValue());
                orders=ordersMapper.selectOne(orders);
                if(null!=orders){
                        shareInfoModel.setIsPay(1); // 分享页面用户展示为已支付
                }else{
                    shareInfoModel.setIsPay(0);//分享页面用户展示为未支付
                }
            }
        }
         List<Member> members= questionBuffMapper.querySharePayMember(param);
        if(members.size()>0){
            shareInfoModel.setMemberList(members);
        }
        ShareTitleBean shareTitleBean=questionBuffMapper.queryShareTitle(param);
        if(null!=shareTitleBean){
            shareInfoModel.setShareTitleBean(shareTitleBean);
        }
        return  ReturnValue.generateTrueReturnValue(shareInfoModel);
    }


    /**
     * 同步赋能信息
     * @param
     * @return
     */
    @Override
    public ReturnValue addUnanimousQuestion(QuestionModel questionModel) {
        ValueOperations<String, QuestionModel> ops = redisTemplate.opsForValue();
        Date date=new Date();
        date=DateUtil.addDay(date,1);
        questionModel.setSynchronizeAt(date);
        String  questionTbId="tb:"+questionModel.getAccountId()+"_"+ToolUtil.createRandomNumber(32);
        questionModel.setQuestionTbId(questionTbId);
        if(null!=questionModel.getDomainId()){
            Domain domain=new Domain();
            domain.setId(questionModel.getDomainId());
            domain=domainMapper.selectOne(domain);
            questionModel.setDomainName(domain.getDomainName());
        }
        ops.set(questionTbId, questionModel, 1, TimeUnit.DAYS);
        pushService.push(questionModel.getAccountId().toString(),"您有新的同步赋能消息");
      return ReturnValue.generateTrueReturnValue("同步成功",questionModel);
    }




    /**
     * 查询赋能同步列表
     * @return
     */
    @Override
    public ReturnValue unanimousQuestionList(QuestionParam param) {
        List<QuestionModel> QuestionModels= new ArrayList<>();
       // Set<String> keys = redisTemplate.keys("tb_*");
        Set<String> keys = redisTemplate.keys("tb:"+param.getUserId()+"_*");
        List<QuestionModel> questionList =redisTemplate.opsForValue().multiGet(keys);
        if(questionList.size()>0){
            Date date=new Date();
            questionList.forEach(questionModel -> {
                if(DateUtil.substruction(date,questionModel.getSynchronizeAt())>=0){
                    QuestionModel questionModel1=new QuestionModel();
                    questionModel1.setTitle(questionModel.getTitle());
                    questionModel1.setId(questionModel.getId());
                    questionModel1.setHour(DateUtil.substruction(date,questionModel.getSynchronizeAt()));
                    questionModel1.setQuestionTbId(questionModel.getQuestionTbId());
                    questionModel1.setSynchronizeAt(questionModel.getSynchronizeAt());
                    QuestionModels.add(questionModel1) ;
                }
            });
            QuestionModels.sort((p, o) -> p.getSynchronizeAt().compareTo(o.getSynchronizeAt()));
            return ReturnValue.generateTrueReturnValue(QuestionModels.get(QuestionModels.size()-1));
        }else{
            return ReturnValue.generateTrueMsgReturnValue("无同步数据");
        }
    }



    /**
     * 通过同步赋能ID查询同步的赋能信息
     * @return
     */
    @Override
    public ReturnValue queryMyTbQuestion(QuestionParam param) {
        Set<String> keys = redisTemplate.keys(param.getQuestionTbId());
        List<QuestionModel> questionList =redisTemplate.opsForValue().multiGet(keys);
        List<Lable> lables=new ArrayList<>();
        String ids = questionList.get(0).getLabelIds();
        if(ids!=null&&!ids.equals(""))
        {
            String[] idArr = ids.split(",");
            for (String id : idArr) {
                Lable lable=new Lable();
                lable.setId(Integer.valueOf(id));
                lable= lableMapper.selectOne(lable);
                lables.add(lable);
            }
            questionList.get(0).setLabelsList(lables);
        }
        return ReturnValue.generateTrueReturnValue(questionList);
    }

    /**
     * 查询我购买的赋能
     * @return
     */
    @Override
    public ReturnValue queryAllQuestionList(QuestionParam param){

        List<QuestionBean> questionBeans=new ArrayList<>();
        if(param.getUserType()==1) {
            List<QuestionListModel> questionListModels = new ArrayList<>();
            questionBeans = questionBuffMapper.queryReleaseQuestionList(param);
            if (null != questionBeans) {
                questionBeans.forEach(questionBean -> {
                    QuestionListModel questionListModel = new QuestionListModel();
                    BeanUtils.copyProperties(questionBean, questionListModel);
                    QuestionParam param1 = new QuestionParam();
                    param1.setQuestionId(questionListModel.getId());
                    List<LableBean> LableBeans = questionBuffMapper.queryLableList(param1);
                    questionListModel.setLables(LableBeans);
                    questionListModels.add(questionListModel);
                });
                QueryList<QuestionListModel> result = new QueryList(questionListModels, Page.toPage(questionBeans));
                return ReturnValue.generateTrueReturnValue(result);
            }
        }

        if(param.getUserType()==2){
         questionBeans =questionBuffMapper.queryBuyQuestionList(param);
        }
        if(param.getUserType()==3){
            questionBeans =questionBuffMapper.queryBuyShareList(param);
        }


        QueryList<QuestionBean> result = new QueryList(questionBeans, Page.toPage(questionBeans));
        return ReturnValue.generateTrueReturnValue(result);
    }

}
